<template>
  <div class="order-detail">
    <!-- 订单进度条 -->
    <el-steps :active="currentStep" align-center finish-status="success">
      <!--      <el-step title="提交订单" :description="formatDate(orderInfo.createTime)"></el-step>-->
      <el-step title="提交订单" :description="orderInfo.order.createTime"></el-step>
      <el-step title="支付订单" description="待支付"></el-step>
      <el-step title="平台发货" description="待发货"></el-step>
      <el-step title="确认收货" description="待确认"></el-step>
      <el-step title="完成评价" description="待评价"></el-step>
    </el-steps>

    <!-- 订单状态 -->
    <el-row :gutter="20" class="order-status">
      <el-col :span="12">
        <el-alert
          :title="'当前订单状态：' + getStatusText(orderInfo.order.status)"
          type="warning"
          :closable="false"
          show-icon>
        </el-alert>
      </el-col>
      <el-col :span="12" class="action-buttons">
        <el-button v-if="orderInfo.order.status==0" @click="modifyAddress" type="primary">修改收货人信息</el-button>
        <el-popconfirm v-if="orderInfo.order.status==0"
                       title="确定关闭该订单吗？"
                       @confirm="closeOrder"
        >
          <el-button slot="reference" style="margin: 0 10px" type="danger">关闭订单</el-button>
        </el-popconfirm>
      </el-col>
    </el-row>

    <!-- 基本信息 -->
    <el-card class="info-section" header="基本信息">
      <el-table :data="[orderInfo.order]" border style="width: 100%">
        <el-table-column prop="orderSn" label="订单编号" width="180" align="center"></el-table-column>
        <el-table-column prop="memberUsername" label="用户账号" width="180" align="center"></el-table-column>
        <el-table-column label="支付方式" align="center">
          <template slot-scope="scope">
            {{ getPaymentType(scope.row.payType) }}
          </template>
        </el-table-column>
        <el-table-column label="订单来源" width="180" align="center">
          <template slot-scope="scope">
            PC订单
          </template>
        </el-table-column>
        <el-table-column label="配送方式" align="center">
          <template slot-scope="scope">
            <!--            delivery_company -->
            {{ scope.row.deliveryCompany ? scope.row.deliveryCompany : '暂无' }}
          </template>
        </el-table-column>

        <el-table-column label="物流单号" align="center">
          <template slot-scope="scope">
            {{ scope.row.deliverySn ? scope.row.deliverySn : '暂无' }}
          </template>
        </el-table-column>
        <el-table-column label="自动确认收货时间" width="180" align="center">
          <template slot-scope="scope">
            {{ scope.row.autoConfirmDay }}天
          </template>
        </el-table-column>
        <el-table-column prop="integration" label="订单可得积分 " align="center"></el-table-column>
        <el-table-column prop="growth" label="订单可得成长值" align="center">
          <template slot-scope="scope">
            {{ scope.row.growth || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="promotionInfo" label="活动信息" align="center"></el-table-column>
      </el-table>
    </el-card>

    <!-- 收货人信息 -->
    <el-card class="info-section" header="收货人信息">
      <el-table :data="[orderInfo.order]" border style="width: 100%">
        <el-table-column prop="receiverName" label="收货人"></el-table-column>
        <el-table-column prop="receiverPhone" label="手机号码"></el-table-column>
        <el-table-column prop="receiverPostCode" label="邮政编码"></el-table-column>
        <el-table-column label="收货地址">
          <template slot-scope="scope">
            {{ getFullAddress(scope.row) }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 商品信息 -->
    <el-card class="info-section" header="商品信息">
      <el-table :data="orderInfo.orderItemList" border style="width: 100%">
        <el-table-column label="商品图片" width="120">
          <template slot-scope="scope">
            <el-image :src="scope.row.productPic" style="width: 80px; height: 80px"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="商品名称">
          <template slot-scope="scope">
            {{ scope.row.productName }}
            <div class="brand">品牌：{{ scope.row.productBrand }}</div>
          </template>
        </el-table-column>
        <el-table-column label="价格/货号">
          <template slot-scope="scope">
            <div>价格：￥{{ scope.row.productPrice }}</div>
            <div>货号：{{ scope.row.productSkuCode || '暂无' }}</div>
          </template>
        </el-table-column>
        <el-table-column label="属性">
          <template slot-scope="scope">
            {{ formatAttr(scope.row.productAttr) }}
          </template>
        </el-table-column>
        <el-table-column prop="productQuantity" label="数量"></el-table-column>
        <el-table-column label="小计">
          <template slot-scope="scope">
            ￥{{ (scope.row.realAmount * scope.row.productQuantity).toFixed(2) }}
          </template>
        </el-table-column>
      </el-table>
      <div class="total-amount">
        合计：<span class="price">￥{{ orderInfo.order.totalAmount.toFixed(2) }}</span>
      </div>
    </el-card>

    <!-- 费用信息 -->
    <el-card class="info-section" header="费用信息">
      <el-table :data="feeData" border style="width: 100%">
        <el-table-column prop="label" label=""></el-table-column>
        <el-table-column prop="value" label="金额" align="center">
          <template slot-scope="scope">
            ￥
            <span v-html=" scope.row.value"></span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>


    <!-- 显示添加或者修改 -->
    <CustomModal :visible.sync="ShowaddRoUpdate" :title="title" @confirm="adOrUpdate">
      <el-form :model="orderInfo.order" label-width="120px">
        <el-form-item label="所在地区:">
          <el-cascader v-model="district" separator="-" :options="options" :props="optionProps"
                       style="width: 350px;" @change="handleChange"/>
        </el-form-item>

        <el-form-item label="详细地址:">
          <el-input style="width: 350px;" v-model="orderInfo.order.receiverDetailAddress"></el-input>
        </el-form-item>

        <el-form-item label="收件人姓名:">
          <el-input style="width: 350px;" v-model="orderInfo.order.receiverName"></el-input>
        </el-form-item>

        <el-form-item label="手机号:">
          <el-input style="width: 350px;" v-model="orderInfo.order.receiverPhone"></el-input>
        </el-form-item>

        <el-form-item label="邮政编号:">
          <el-input style="width: 350px;" v-model="orderInfo.order.receiverPostCode"></el-input>
        </el-form-item>
      </el-form>
    </CustomModal>
  </div>
</template>

<script>
import {Steps, Step, Row, Col, Alert, Button, Card, Table, TableColumn, Image} from 'element-ui';
import {getOrderDetail, updateOrder} from "@/api/order/order";
import {listAddress} from "@/api/common/common"
import CustomModal from "@/components/CustomModal/CustomModal"

export default {
  name: 'OrderDetail',
  components: {
    'el-steps': Steps,
    'el-step': Step,
    'el-row': Row,
    'el-col': Col,
    'el-alert': Alert,
    'el-button': Button,
    'el-card': Card,
    'el-table': Table,
    'el-table-column': TableColumn,
    'el-image': Image,
    CustomModal
  },
  data() {
    return {
      ShowaddRoUpdate: false,
      type: 0, // 0 for add, 1 for update
      title: '修改地址',
      currentStep: 1,
      orderInfo: {
        order: {
          totalAmount: 0,
          realAmount: 0,
          productQuantity: 0
        },
        orderItemList: [],
      },
      district: [],
      feeData: [],
      options: [],
      optionProps: {
        value: "name",
        label: "name",
        children: "children",
      },
    };
  },

  methods: {
    closeOrder() {
      // 关闭订单
      this.orderInfo.order.status = 4;
      updateOrder(this.orderInfo.order).then(res => {
        if (res.code == 200) {
          this.getOrderList(this.$route.query.id)
          this.$message.success("已关闭订单")
        } else {
          this.$message.error("关闭订单失败")
        }

      })
    },
    adOrUpdate() {
      let formToSubmit = this.orderInfo.order;
      if (this.district.length == 0) {
        Message.warning("地区不能为空~");
        return;
      } else if (formToSubmit.receiverDetailAddress == "") {
        Message.warning("详细地址不能为空~");
        return;
      } else if (formToSubmit.receiverName == "") {
        Message.warning("收件人不能为空~");
        return;
      } else if (formToSubmit.receiverPostCode == "") {
        Message.warning("邮政编码不能为空~");
        return;
      } else if (formToSubmit.phoneNumber == "") {
        Message.warning("手机号不能为空~");
        return;
      }

      let reg = /^1[13456789]\d{9}$/;
      if (!reg.test(formToSubmit.receiverPhone)) {
        Message.warning("手机号格式不正确~");
        return;
      }

      let arr = [];
      if (this.type == 0) {
        arr = this.area.split('-');
      } else {
        arr = this.district
      }
      if (arr[2] == "undefined") { //说明 区没有
        formToSubmit.receiverProvince = arr[0];
        formToSubmit.receiverCity = arr[1];
      } else {
        formToSubmit.receiverProvince = arr[0];
        formToSubmit.receiverCity = arr[1];
        formToSubmit.receiverRegion = arr[2];
      }
      updateOrder(formToSubmit).then(res => {
        if (res.code == 200) {
          this.getOrderList(this.$route.query.id)
          this.ShowaddRoUpdate = false;
          this.$message.success("修改成功")
        } else {
          this.$message.error("修改失败")
        }
      })

    },
    handleChange(arr) {
      this.area = `${arr[0]}-${arr[1]}-${arr[2]}`;
    },
    getOrderList(id) {
      getOrderDetail(id).then(res => {
        if (res.code == 200) {
          this.orderInfo = res.data;
          this.feeData = [
            {label: '商品合计', value: res.data.order.totalAmount | '-0'},
            {label: '运费', value: '0'},
            {label: '优惠券', value: res.data.order.couponAmount | '-0'},
            {label: '积分抵扣', value: res.data.order.integrationAmount | '-0'},
            {label: '活动优惠', value: res.data.order.promotionAmount | '-0'},
            {label: '折扣金额', value: res.data.order.discountAmount | '-0'},
            {label: '订单总金额', value: `<strong style="color: #ff4d4f;">${res.data.order.totalAmount}</strong>`},
            {label: '应付款金额', value: `<strong style="color: #ff4d4f;">${res.data.order.payAmount}</strong>`}
          ]
          if (res.data.order.status==4){
            this.currentStep=1
          }else {
            this.currentStep=res.data.order.status+1
          }

          if (res.data.order.status == 0) {
            this.getAdderssList()
          }
        }
      })
    },
    getAdderssList() {
      listAddress().then((res) => {
        if (res.code == 200) {
          this.options = this.filterOptions(res.data)
          this.district = [this.orderInfo.order.receiverProvince,
            this.orderInfo.order.receiverCity,

          ]
          if (this.orderInfo.order.receiverRegion != "") {
            this.district.push(this.orderInfo.order.receiverRegion)
          }
          console.log(this.district)
        }
      });
    },
    filterOptions(options) {
      return options.filter(option => {
        if (option.children) {
          // 递归处理子级
          option.children = this.filterOptions(option.children);
          // 如果处理后的子级为空，则直接删除children属性
          if (option.children.length === 0) {
            delete option.children;
          }
        }
        // 保留有子级或本身没有子级的节点
        return !option.children || option.children.length > 0;
      });
    },
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
    },
    getStatusText(status) {
      console.log(status)
      const statusMap = {
        0: '待付款',
        1: '待发货',
        2: '已发货',
        3: '已完成',
        4: '已关闭'
      };
      return statusMap[status] || '未知状态';
    },
    getPaymentType(type) {
      const paymentMap = {
        1: '支付宝',
        2: '微信支付',
        3: '银行卡支付'
      };
      return paymentMap[type] || '未支付';
    },
    getFullAddress(order) {
      return `${order.receiverProvince} ${order.receiverCity} ${order.receiverRegion} ${order.receiverDetailAddress}`;
    },
    formatAttr(attrStr) {
      if (!attrStr) return '';
      try {
        const attrs = JSON.parse(attrStr);
        return attrs.map(attr => `${attr.key}: ${attr.value}`).join('; ');
      } catch (e) {
        return attrStr;
      }
    },
    modifyAddress() {
      // 修改收货人信息
      this.ShowaddRoUpdate = true
    },
    modifyBilling() {
      // 修改费用信息
    },
    updateLogistics() {
      // 发送站内信
    },
  },
  created() {
    if (this.$route.query.id) {
      this.getOrderList(this.$route.query.id)
    }

    this.currentStep = this.orderInfo.status + 1; // 假设status从0开始
  }
};
</script>

<style scoped>
.order-detail {
  padding: 20px;
}

.total-amount {
  text-align: right;
  padding: 15px;
  border: 1px solid #e8e8e8;
  border-top: none;
}

.price {
  color: #ff4d4f;
  font-size: 16px;
  font-weight: bold;
}

.brand {
  color: #999;
  font-size: 12px;
  margin-top: 5px;
}

.el-alert {
  margin-bottom: 10px;
}

.el-button + .el-button {
  margin-left: 10px;
}

.el-table {
  margin-top: 15px;
}

.el-card {
  margin-bottom: 20px;
}

.el-card__header {
  background-color: #f8f8f8;
}

.el-steps {
  margin-bottom: 20px;
}
</style>
